package echat.future.cn.echat.netease;

import android.content.Context;

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.Volley;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.RequestCallback;
import com.netease.nimlib.sdk.auth.AuthService;
import com.netease.nimlib.sdk.auth.LoginInfo;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import echat.future.cn.echat.my.utils.UserHelper;
import lumingweihua.future.cn.baselibgxh.base.MyApplication;
import lumingweihua.future.cn.baselibgxh.utils.MD5;
import lumingweihua.future.cn.baselibgxh.utils.SharedPreference;

/**
 * Created by Administrator on 2018/8/23.
 */

public class NeteaseLoginUtil {

    private String account;

    public NeteaseLoginUtil(String account) {
        this.account = account;
    }

    public void loginNetease(Context context){
        LoginInfo info = new LoginInfo(account, MD5.Md5(account));
        RequestCallback<LoginInfo> callback =
                new RequestCallback<LoginInfo>() {
                    @Override
                    public void onSuccess(LoginInfo param) {
                        SharedPreference.saveToSP(context,"neteaseToken",param.getToken());
                        SharedPreference.saveToSP(context,"neteaseAccount",account);
                        MyApplication.getInstance().setNeteaseToken(param.getToken());
//                        System.out.println("account="+param.getAccount());
//                        System.out.println("token="+param.getToken());
                    }

                    @Override
                    public void onFailed(int code) {
                        //登录失败，注册   302 密码不对
                        System.out.println("code="+code);
                        if(code == 302){
                            Volley.newRequestQueue(context).add(new NeteaseLoginRequest("https://api.netease.im/nimserver/user/create.action", new RegisterListener() {
                                @Override
                                public void onRegisterSuccess() {
                                    //注册成功 登录
                                    loginNetease(context);
                                }

                                @Override
                                public void onRegisterFail() {
                                    Volley.newRequestQueue(context).add(new NeteaseUpdateRequest("https://api.netease.im/nimserver/user/update.action", new RegisterListener() {
                                        @Override
                                        public void onRegisterSuccess() {
                                            //更新成功
                                            loginNetease(context);
                                        }

                                        @Override
                                        public void onRegisterFail() {

                                        }
                                    }, new Response.ErrorListener() {
                                        @Override
                                        public void onErrorResponse(VolleyError error) {
                                            //注册失败
                                            //更新密码
                                            System.out.println("更新失败");
                                        }
                                    }));
                                }
                            }, new Response.ErrorListener() {
                                @Override
                                public void onErrorResponse(VolleyError error) {
                                    //注册失败
                                    //更新密码
                                    System.out.println("注册失败");
                                }
                            }));
                        }

                    }

                    @Override
                    public void onException(Throwable exception) {

                    }
                    // 可以在此保存LoginInfo到本地，下次启动APP做自动登录用
                };
        NIMClient.getService(AuthService.class).login(info)
                .setCallback(callback);
    }

    class NeteaseLoginRequest extends Request<String> {

        RegisterListener listener;
        public NeteaseLoginRequest(String url,RegisterListener listener, Response.ErrorListener errorlistener) {
            super(Request.Method.POST, url, errorlistener);
            this.listener = listener;
        }

        @Override
        protected Response<String> parseNetworkResponse(NetworkResponse response) {
            String parsed = null;
            try {
                parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
            } catch (UnsupportedEncodingException e) {
                parsed = new String(response.data);
            }
            return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response));
        }

        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            Map<String, String> headers = new HashMap<String, String>();
            // 设置请求的header
            String appKey = "5241ad7f29be9a0707808bfe75054c4a";
            String CurTime = String.valueOf((new Date()).getTime() / 1000L);
            String Nonce = "123456";
            String checkSum = CheckSumBuilder.getCheckSum("dcc097b37661", Nonce ,CurTime);

            headers.put("AppKey", appKey);
            headers.put("Nonce", Nonce);
            headers.put("CurTime", CurTime);
            headers.put("checkSum", checkSum);
            headers.put("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");

            return headers;
        }

        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            Map<String, String> querys = new HashMap<String, String>();
            querys.put("accid", account);
            querys.put("token", MD5.Md5(account));
//            querys.put("name", UserHelper.getUser().getUsername());
//            querys.put("icon", UserHelper.getUser().getAvatar());
            return querys;
        }

        @Override
        protected void deliverResponse(String response) {
            //注册成功
            try {
                JsonParser parser = new JsonParser();
                JsonElement jsonElement = parser.parse(response);
                if(jsonElement.getAsJsonObject().get("code").getAsString().equals("200")){
                    listener.onRegisterSuccess();
                }else
                    listener.onRegisterFail();
            } catch (Exception e) {
                // TODO: handle exception
            }

        }
    }

    class NeteaseUpdateRequest extends Request<String> {

        RegisterListener listener;
        public NeteaseUpdateRequest(String url,RegisterListener listener, Response.ErrorListener errorlistener) {
            super(Request.Method.POST, url, errorlistener);
            this.listener = listener;
        }

        @Override
        protected Response<String> parseNetworkResponse(NetworkResponse response) {
            String parsed = null;
            try {
                parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
            } catch (UnsupportedEncodingException e) {
                parsed = new String(response.data);
            }
            return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response));
        }

        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            Map<String, String> headers = new HashMap<String, String>();
            // 设置请求的header
            String appKey = "5241ad7f29be9a0707808bfe75054c4a";
            String CurTime = String.valueOf((new Date()).getTime() / 1000L);
            String Nonce = "123456";
            String checkSum = CheckSumBuilder.getCheckSum("dcc097b37661", Nonce ,CurTime);

            headers.put("AppKey", appKey);
            headers.put("Nonce", Nonce);
            headers.put("CurTime", CurTime);
            headers.put("checkSum", checkSum);
            headers.put("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");

            return headers;
        }

        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            Map<String, String> querys = new HashMap<String, String>();
            querys.put("accid", account);
            querys.put("token", MD5.Md5(account));
            return querys;
        }

        @Override
        protected void deliverResponse(String response) {
            //注册成功
            System.out.println("neteaseUpdateresponse="+response);
            try {
                JsonParser parser = new JsonParser();
                JsonElement jsonElement = parser.parse(response);
                if(jsonElement.getAsJsonObject().get("code").getAsString().equals("200")){
                    listener.onRegisterSuccess();
                }
            } catch (Exception e) {
                // TODO: handle exception
            }

        }
    }

    interface RegisterListener{
        void onRegisterSuccess();
        void onRegisterFail();
    }


}
